<template>
  <div>
    <scroll-page
      :loading="loading"
      :offset="offset"
      :no-data="noData"
      v-on:load="load"
    >
      <article-item v-for="a in articles" :key="a.id" v-bind="a"></article-item>
    </scroll-page>
  </div>
</template>

<script>
import ArticleItem from "@/components/article/ArticleItem";
import ScrollPage from "@/components/scrollpage";
import { getArticles } from "@/api/blog";

export default {
  name: "ArticleScrollPage",
  props: {
    offset: {
      type: Number,
      default: 100,
    },
    page: {
      type: Object,
      default() {
        return {};
      },
    },
    query: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  watch: {
    query: {
      handler() {
        this.noData = false;
        this.articles = [];
        this.innerPage.pageNo = 1;
        this.getArticles();
      },
      deep: true,
    },
    page: {
      handler() {
        this.noData = false;
        this.articles = [];
        this.innerPage = this.page;
        this.getArticles();
      },
      deep: true,
    },
  },
  data() {
    return {
      loading: false,
      noData: false,
      innerPage: {
        pageSize: 10,
        pageNo: 1,
        name: "create_time",
        sort: "desc",
      },
      articles: [],
    };
  },
  components: {
    "article-item": ArticleItem,
    "scroll-page": ScrollPage,
  },
  methods: {
    load() {
      this.getArticles();
    },
    view(id) {
      this.$router.push({ path: `/article/view/${id}` });
    },
    getArticles() {
      let that = this;
      that.loading = true;

      getArticles(that.query, that.innerPage)
        .then((resp) => {
          if (resp.result != null) {
            let newArticles = resp.result.list;
            that.innerPage.pageNo += 1;
            that.articles = that.articles.concat(newArticles);
            this.postFather(resp.result.total);
            console.log("传递成功");
          } else {
            that.noData = true;
            that.$message({
              type: "warning",
              message: resp.message,
              showClose: true,
            });
          }
        })
        .catch((error) => {
          if (error !== "error") {
            that.$message({
              type: "warning",
              message: "文章加载失败!",
              showClose: true,
            });
          }
        })
        .finally(() => {
          that.loading = false;
        });
    },
    postFather(number) {
      this.$emit("post_total", number);
    },
  },
  created() {
    this.getArticles();
  },
};
</script>

<style scoped>
.el-card {
  border-radius: 0;
}

.el-card:not(:first-child) {
  margin-top: 10px;
}
</style>
